package com.lagou.zkweb;

import lombok.Data;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

@Data
public class DruidManager {

    private static List<Connection> pool = new ArrayList<>();

    public static void createConnectPool() throws Exception {
        createConnect();
    }

    private static void createConnect() throws Exception {
        Properties properties = CommonUtil.dbProperties;
        Class.forName(properties.getProperty("driverClassName"));
        Connection connection = DriverManager.getConnection(
                properties.getProperty("url"),
                properties.getProperty("username"),
                properties.getProperty("password")
        );

        pool.add(connection);
    }

    public static Connection getConnection() {
        if (pool.size() > 0) {
            return pool.get(0);
        } else {
            try {
                createConnect();
                return pool.get(0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void close() {
        try {
            for (Connection connection : pool) {
                connection.close();
            }
            pool = new ArrayList<>();
        } catch (Exception e) {

        }
    }
}
